package com.shw.loco.adapter;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Environment;
import android.util.Log;

import com.shw.loco.database.DataType;
import com.shw.loco.database.DatabaseHelper;
import com.shw.loco.util.InfoUtils;
import com.shw.loco.vo.AREADBInfo;
import com.shw.loco.vo.GPSBDInfo;
import com.shw.loco.vo.RFIDBoardInfo;
import com.shw.loco.vo.RFIDDBInfo;
import com.shw.loco.vo.SendInfo;

/**
 * 
 * @author HAHA
 * 
 */
public class LocoCalRFIDThread extends Thread {

	private DatabaseHelper databaseHelper;
	private String operFlag = "add";
	private String precisionInfo = "1.5";
	private SharedPreferences sharedPreferences;
	private String ISDEBUG="realse";
	public LocoCalRFIDThread(Context context,
			SharedPreferences sharedPreferences) {
		databaseHelper = new DatabaseHelper(context);
		operFlag = sharedPreferences.getString(InfoUtils.OPERFLAG, "add");
		precisionInfo= sharedPreferences.getString(InfoUtils.PRECISION_IFNO, "1.5");
//		ISDEBUG=sharedPreferences.getString(InfoUtils.ISDEBUG, "release");
		InfoUtils.TERMINALID = sharedPreferences.getString(InfoUtils.LOCOTERMINAL, "0000");
		this.sharedPreferences=sharedPreferences;
		if(ISDEBUG.equalsIgnoreCase("debug"))
		newFile();
	}

	//////////////////////////////////////////////////
	BufferedWriter bwe;
	private void newFile(){
		String pathString = Environment.getExternalStorageDirectory().getPath()
				+ "/shw_recore.TXT";
		File file=new File(pathString);
		
		/*if(!file.exists()){
			try {
				file.createNewFile();
				
			} catch (IOException e) {
			}
		}*/
		try {
			bwe=new BufferedWriter(new FileWriter(file,true));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
	}
	
	private void writeInfo(String info,BufferedWriter bws){
		try {
			bws.append(info+new Date().toGMTString()+"\n");
			bws.append("-------------------"+"\n");
			bws.flush();
		} catch (IOException e) {
		}
	}
	
	private void getRFIDDBInfo(RFIDDBInfo rinfo){
		if(ISDEBUG.equalsIgnoreCase("debug"))
		writeInfo(rinfo.toRFIDDBInfo(), bwe);
	}
	
	private void getAreadbInfos(AREADBInfo ainfo){
		if(ISDEBUG.equalsIgnoreCase("debug"))
		writeInfo("RFID-GPS "+ainfo.toAreaInfo(), bwe);
	}
	private void getAreadbInfo(AREADBInfo ainfo){
		if(ISDEBUG.equalsIgnoreCase("debug"))
		writeInfo(ainfo.toAreaInfo(), bwe);
	}
	private void getInfo(String ainfo){
		if(ISDEBUG.equalsIgnoreCase("debug"))
		writeInfo("CENTER: "+ainfo, bwe);
	}
	/////////////////////////////////////////////////////
	
	public RFIDDBInfo queryRFID(RFIDBoardInfo boardInfo) {
		RFIDDBInfo rfiddbInfo = null;
		Cursor cursor = databaseHelper.query(DataType.RFID, "rfid='"
				+ boardInfo.getRf1ID() + "'");
		if (cursor.moveToFirst()) {
			rfiddbInfo = setRFIDDBInfo(cursor);
		} else if (boardInfo.getRfCount() > 1) {
			cursor = databaseHelper.query(DataType.RFID,
					"rfid='" + boardInfo.getRf2ID() + "'");
			if (cursor.moveToFirst()) {
				rfiddbInfo = setRFIDDBInfo(cursor);
			}
		}
		return rfiddbInfo;
	}

	public AREADBInfo queryAreaByRFID(RFIDDBInfo rfiddbInfo) {
		AREADBInfo areadbInfo = null;
		String sql = "select t.*,t.mile_coor-"
				+ rfiddbInfo.getRfid_coordinate()
				+ " ds from area t where ds>=0  order by ds ";
		Cursor cursor = databaseHelper.query(sql);
		if (cursor.moveToFirst()) {
			areadbInfo = setAreaDBInfo(cursor);
		}
		return areadbInfo;
	}

	public AREADBInfo queryAreaByGPS(GPSBDInfo gpsbdInfo) {
		AREADBInfo areadbInfo = null;
		if (gpsbdInfo != null) {
			String sql = "select t.*,t.latlon-(" + gpsbdInfo.getGbLat() + "+"
					+ gpsbdInfo.getGbLon()
					+ ") ds from area t where ds>=0  order by ds ";
			Cursor cursor = databaseHelper.query(sql);
			if (cursor.moveToFirst()) {
				areadbInfo = setAreaDBInfo(cursor);
			}
		}
		return areadbInfo;
	}

	public AREADBInfo setAreaDBInfo(Cursor cursor) {
		AREADBInfo areadbInfo = new AREADBInfo();
		areadbInfo.setLon(cursor.getString(cursor.getColumnIndex("lon")));
		areadbInfo.setLat(cursor.getString(cursor.getColumnIndex("lat")));
		areadbInfo.setMile_coor(cursor.getString(cursor
				.getColumnIndex("mile_coor")));
		areadbInfo.setAreano(cursor.getString(cursor.getColumnIndex("areano")));
		areadbInfo.setTrack(cursor.getString(cursor.getColumnIndex("track")));
		// areadbInfo.setLon(cursor.getString(cursor.getColumnIndex("switch")));
		areadbInfo.setLatlon(cursor.getString(cursor.getColumnIndex("latlon")));
		return areadbInfo;
	}

	public RFIDDBInfo setRFIDDBInfo(Cursor cursor) {
		RFIDDBInfo rfiddbInfo = new RFIDDBInfo();
		rfiddbInfo.setRfid(cursor.getString(cursor.getColumnIndex("rfid")));
//		rfiddbInfo.setRfid_effect(Integer.valueOf(cursor.getString(cursor.getColumnIndex("rfid_effect"))));
		rfiddbInfo.setRfid_track(cursor.getString(cursor
				.getColumnIndex("rfid_track")));
		rfiddbInfo.setRfid_coordinate(cursor.getString(cursor
				.getColumnIndex("rfid_coordinate")));
//		rfiddbInfo.setRfid_switchnum(cursor.getString(cursor.getColumnIndex("rfid_switchnum")));
//		rfiddbInfo.setRfid_crossnum(cursor.getString(cursor.getColumnIndex("rfid_crossnum")));
//		rfiddbInfo.setRfid_crossdirection(cursor.getString(cursor.getColumnIndex("rfid_crossdirection")));
//		rfiddbInfo.setRfid_relpostion(cursor.getString(cursor.getColumnIndex("rfid_relpostion")));
//		rfiddbInfo.setRfid_targetpostion(cursor.getString(cursor.getColumnIndex("rfid_targetpostion")));
		rfiddbInfo.setRfid_lat(cursor.getString(cursor.getColumnIndex("lon")));
		rfiddbInfo.setRfid_lon(cursor.getString(cursor.getColumnIndex("lat")));
		rfiddbInfo.setRfid_latlon(cursor.getString(cursor
				.getColumnIndex("latlon")));
		rfiddbInfo.setRfid_areano(cursor.getString(cursor
				.getColumnIndex("areano")));
		return rfiddbInfo;
	}

	public String getFlagStr(RFIDBoardInfo boardInfo, boolean flag) {
		StringBuffer sb = new StringBuffer();
		if (boardInfo.getRfCourse().equals("00")) {// 顺时针为上行
			sb.append("0");
		} else {// 逆时针为下行
			sb.append("1");
		}
		if (LocoInfoQueue.gpsbdVector.size() > 0) {// GPS已经定定位
			sb.append("1");
		} else {// GPS未定位
			sb.append("0");
		}
		sb.append("00");
		switch (boardInfo.getRfCount()) {
		case 1:
			sb.append("1");
			break;
		case 2:
			sb.append("0");
			break;
		default:
			break;
		}
		if (flag) {
			sb.append("1");
		} else {
			sb.append("0");
		}
		sb.append("0000000000");
		return sb.toString();
	}
 
	@Override
	public void run() {
		super.run();
		while (!isInterrupted()) {
			RFIDBoardInfo boardInfo =null;
			SendInfo sendInfo = null;
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			boardInfo=null;
			 boardInfo = LocoInfoQueue.getRFIDBoardInfo();
			AREADBInfo GPSareadbInfo = null;
			if (boardInfo != null) { // 查库 计算 RFIDDBInfo
				RFIDDBInfo rfiddbInfo = null;
				rfiddbInfo = queryRFID(boardInfo);// 根据rfid信息获取RFID数据表信息
//				rfiddbInfo.setRfid_coordinate(new BigDecimal(rfiddbInfo.getRfid_coordinate()).add(new BigDecimal(boardInfo.getRfMil())).toString());
				//根据方向来计算rfid的里程坐标
				
				try {
					GPSareadbInfo = queryAreaByGPS(boardInfo.getGpsbdInfo());// 根据RFID同时获取的gps信息获取对应区间表信息
				} catch (Exception e) {
					Log.d("LocoCalRFIDThread", "error1");
				}
				sendInfo = new SendInfo();
				sendInfo.setTerminalid(InfoUtils.leftAdding(InfoUtils.TERMINALID,"0",4));
				if (rfiddbInfo != null) {
					if (boardInfo.getRfCourse().equals("00")) {
						if (operFlag.equals("add")) { 
							rfiddbInfo.setRfid_coordinate(
									new BigDecimal(rfiddbInfo
											.getRfid_coordinate()).add(
											new BigDecimal(boardInfo
													.getRfMil()))
											.toString());
							rfiddbInfo.setRfid_coordinate0x(InfoUtils.coor2HexString(
									rfiddbInfo.getRfid_coordinate(), false));
							/*sendInfo.setSdMilCoordinate(InfoUtils.coor2HexString(
									new BigDecimal(rfiddbInfo
											.getRfid_coordinate()).add(
											new BigDecimal(boardInfo
													.getRfMil()))
											.toString(), false));*/
						} else {
							rfiddbInfo.setRfid_coordinate(
									new BigDecimal(rfiddbInfo
											.getRfid_coordinate())
											.subtract(
													new BigDecimal(
															boardInfo
																	.getRfMil()))
											.toString());
							rfiddbInfo.setRfid_coordinate0x(InfoUtils.coor2HexString(
									rfiddbInfo.getRfid_coordinate(), false));
							/*sendInfo.setSdMilCoordinate(InfoUtils.coor2HexString(
									new BigDecimal(rfiddbInfo
											.getRfid_coordinate())
											.subtract(
													new BigDecimal(
															boardInfo
																	.getRfMil()))
											.toString(), false));*/
						}
					} else {
						if (!operFlag.equals("add")) {
							rfiddbInfo.setRfid_coordinate(
									new BigDecimal(rfiddbInfo
											.getRfid_coordinate()).add(
											new BigDecimal(boardInfo
													.getRfMil()))
											.toString());
							rfiddbInfo.setRfid_coordinate0x(InfoUtils.coor2HexString(
									rfiddbInfo.getRfid_coordinate(), false));
							/*sendInfo.setSdMilCoordinate(InfoUtils.coor2HexString(
									new BigDecimal(rfiddbInfo
											.getRfid_coordinate()).add(
											new BigDecimal(boardInfo
													.getRfMil()))
											.toString(), false));*/
						} else {
							rfiddbInfo.setRfid_coordinate(
									new BigDecimal(rfiddbInfo
											.getRfid_coordinate())
											.subtract(
													new BigDecimal(
															boardInfo
																	.getRfMil()))
											.toString());
							rfiddbInfo.setRfid_coordinate0x(InfoUtils.coor2HexString(
									rfiddbInfo.getRfid_coordinate(), false));
							/*sendInfo.setSdMilCoordinate(InfoUtils.coor2HexString(
									new BigDecimal(rfiddbInfo
											.getRfid_coordinate())
											.subtract(
													new BigDecimal(
															boardInfo
																	.getRfMil()))
											.toString(), false));*/
						}
					}
					//调试日志-记录根据rfid信息获取RFID数据表信息
					getRFIDDBInfo(rfiddbInfo);
					operFlag = sharedPreferences.getString(InfoUtils.OPERFLAG, "add");
					try {
						AREADBInfo RFareadbInfo = null;
						RFareadbInfo = queryAreaByRFID(rfiddbInfo);
						if(RFareadbInfo==null){
							if (LocoInfoQueue.gpsbdVector.size() > 0) {
								sendInfo = new SendInfo();
								GPSBDInfo gpsbdinfoNoRFID = LocoInfoQueue.gpsbdVector
										.remove(0);
								GPSareadbInfo = queryAreaByGPS(gpsbdinfoNoRFID);
								if (GPSareadbInfo != null) {
									try {
										getAreadbInfo(GPSareadbInfo);
										sendInfo.setSdDate(InfoUtils.dateToHexStrNoCRC());
										sendInfo.setSdTrackNo(InfoUtils.int2HexString(
												GPSareadbInfo.getTrack(), 2));
										sendInfo.setSdAreaNo(InfoUtils.int2HexString(
												GPSareadbInfo.getAreano(), 4));
										sendInfo.setSdFlag(InfoUtils
												.binaryString2HexString("0100110000000000",
														4));
										sendInfo.setSdMilCoordinate(InfoUtils
												.coor2HexString(
														GPSareadbInfo.getMile_coor(), false));
										sendInfo.setSdSpeed(InfoUtils.int2HexString(
												InfoUtils.strCal1b(gpsbdinfoNoRFID
														.getGbSpeed()), 4));
										sendInfo.setSdLon(InfoUtils.int2HexString(
												InfoUtils.strCal1bw(GPSareadbInfo.getLon()),
												8));
										sendInfo.setSdLat(InfoUtils.int2HexString(
												InfoUtils.strCal1bw(GPSareadbInfo.getLat()),
												8));
										sendInfo.setSdMilRFID("00000000");
										sendInfo.setSdStatus("01");// 00rfid计算得出 01gps计算得到
																	// 02里程计算得出
										sendInfo.setSdReserve("00000000");
										LocoInfoQueue.resultToCenterVector.add(InfoUtils
												.HexToByteArr(sendInfo.toNetString()));
//										LocoInfoQueue.resultToLocoVector.add(InfoUtils.HexToByteArr(sendInfo.toRSString()));
										getInfo(sendInfo.toRSString());
										/*
										 * if (LocoInfoQueue.locoRFIDQueVecotr.size() > 0)
										 * try {
										 * LocoInfoQueue.resultToLocoVector.add(InfoUtils
										 * .HexToByteArr(sendInfo.toRSString())); } catch
										 * (Exception e) {
										 * System.out.println(e.getMessage()); }
										 */
									} catch (Exception e) {
										Log.d("LocoCalRFIDThread", "error4");
									}
								}
							}
						}else{
						getAreadbInfos(RFareadbInfo);
						if (GPSareadbInfo == null) {
							sendInfo.setSdStatus("02");// 00rfid计算得出
														// 01gps计算得到02里程计算得出
							sendInfo.setSdFlag(InfoUtils
									.binaryString2HexString(
											getFlagStr(boardInfo, false), 4));
							sendInfo.setSdMilCoordinate(rfiddbInfo.getRfid_coordinate0x());
						} else {
							getAreadbInfo(GPSareadbInfo);
							sendInfo.setSdStatus("00");// 00rfid计算得出 01gps计算得到
														// 02里程计算得出
							boolean compareReult = false;
							compareReult = InfoUtils.compareInfo(
									RFareadbInfo.getMile_coor(),
									GPSareadbInfo.getMile_coor(), precisionInfo);
							if (compareReult) {// 使用GPS里程坐标
								sendInfo.setSdFlag(InfoUtils
										.binaryString2HexString(
												getFlagStr(boardInfo,
														compareReult), 4));
								sendInfo.setSdMilCoordinate(InfoUtils
										.coor2HexString(
												RFareadbInfo.getMile_coor(),
												false));
							} else {// 使用rfid里程坐标
								sendInfo.setSdFlag(InfoUtils
										.binaryString2HexString(
												getFlagStr(boardInfo,
														compareReult), 4));
								/*if (boardInfo.getRfCourse().equals("00")) {
									if (operFlag.equals("add")) {
										sendInfo.setSdMilCoordinate(InfoUtils.coor2HexString(
												new BigDecimal(rfiddbInfo
														.getRfid_coordinate())
														.add(new BigDecimal(
																boardInfo
																		.getRfMil()))
														.toString(), false));
									} else {
										sendInfo.setSdMilCoordinate(InfoUtils.coor2HexString(
												new BigDecimal(rfiddbInfo
														.getRfid_coordinate())
														.subtract(
																new BigDecimal(
																		boardInfo
																				.getRfMil()))
														.toString(), false));
									}
								} else {
									if (!operFlag.equals("add")) {
										sendInfo.setSdMilCoordinate(InfoUtils.coor2HexString(
												new BigDecimal(rfiddbInfo
														.getRfid_coordinate())
														.add(new BigDecimal(
																boardInfo
																		.getRfMil()))
														.toString(), false));
									} else {
										sendInfo.setSdMilCoordinate(InfoUtils.coor2HexString(
												new BigDecimal(rfiddbInfo
														.getRfid_coordinate())
														.subtract(
																new BigDecimal(
																		boardInfo
																				.getRfMil()))
														.toString(), false));
									}
								}*/
								sendInfo.setSdMilCoordinate(rfiddbInfo.getRfid_coordinate0x());
							}
						}
						sendInfo.setSdDate(boardInfo.getRfDate0x());
						sendInfo.setSdTrackNo(InfoUtils.int2HexString(
								rfiddbInfo.getRfid_track(), 2));
						sendInfo.setSdAreaNo(InfoUtils.int2HexString(
								RFareadbInfo.getAreano(), 4));
						//速度计算有待修改
						sendInfo.setSdSpeed(InfoUtils.int2HexString(
								InfoUtils.strCal1b(boardInfo.getRfSpeed()), 4).substring(0, 4));

						sendInfo.setSdLon(InfoUtils.int2HexString(
								InfoUtils.strCal1bw(RFareadbInfo.getLon()), 8));
						sendInfo.setSdLat(InfoUtils.int2HexString(
								InfoUtils.strCal1bw(RFareadbInfo.getLat()), 8));

						sendInfo.setSdMilRFID(boardInfo.getRfMil0x());

						sendInfo.setSdReserve("00000000");
						
						LocoInfoQueue.resultToCenterVector.add(InfoUtils
								.HexToByteArr(sendInfo.toNetString()));
//						LocoInfoQueue.resultToLocoVector.add(InfoUtils.HexToByteArr(sendInfo.toRSString()));
						LocoInfoQueue.gpsbdVector.clear();
						getInfo(sendInfo.toRSString());}
					} catch (Exception e) {
						Log.d("LocoCalRFIDThread", "error2");
					}
				} else {// 使用GPS定位

					if (LocoInfoQueue.gpsbdVector.size() > 0) {

						GPSBDInfo gpsbdinfoNoRFID = LocoInfoQueue.gpsbdVector
								.remove(0);
						GPSareadbInfo = queryAreaByGPS(gpsbdinfoNoRFID);
						if (GPSareadbInfo != null) {
							try {
								getAreadbInfo(GPSareadbInfo);
								sendInfo.setSdDate(InfoUtils
										.dateToHexStrNoCRC());
								sendInfo.setSdTrackNo(InfoUtils.int2HexString(
										GPSareadbInfo.getTrack(), 2));
								sendInfo.setSdAreaNo(InfoUtils.int2HexString(
										GPSareadbInfo.getAreano(), 4));
								sendInfo.setSdFlag(InfoUtils
										.binaryString2HexString(
												"0100110000000000", 4));
								sendInfo.setSdMilCoordinate(InfoUtils
										.coor2HexString(
												GPSareadbInfo.getMile_coor(),
												false));
								sendInfo.setSdSpeed(InfoUtils.int2HexString(
										InfoUtils.strCal1b(gpsbdinfoNoRFID
												.getGbSpeed()), 4));
								sendInfo.setSdLon(InfoUtils.int2HexString(
										InfoUtils.strCal1bw(GPSareadbInfo
												.getLon()), 8));
								sendInfo.setSdLat(InfoUtils.int2HexString(
										InfoUtils.strCal1bw(GPSareadbInfo
												.getLat()), 8));
								sendInfo.setSdMilRFID("00000000");
								sendInfo.setSdStatus("01");// 00rfid计算得出
															// 01gps计算得到
															// 02里程计算得出
								sendInfo.setSdReserve("00000000");
								LocoInfoQueue.resultToCenterVector
										.add(InfoUtils.HexToByteArr(sendInfo
												.toNetString()));
//								LocoInfoQueue.resultToLocoVector.add(InfoUtils.HexToByteArr(sendInfo.toRSString()));
								getInfo(sendInfo.toRSString());
							} catch (Exception e) {
								Log.d("LocoCalRFIDThread", "error3");
							}
						}
					}
				}

			} else {// 使用GPS定位

				if (LocoInfoQueue.gpsbdVector.size() > 0) {
					sendInfo = new SendInfo();
					GPSBDInfo gpsbdinfoNoRFID = LocoInfoQueue.gpsbdVector
							.remove(0);
					GPSareadbInfo = queryAreaByGPS(gpsbdinfoNoRFID);
					if (GPSareadbInfo != null) {
						try {
							getAreadbInfo(GPSareadbInfo);
							sendInfo.setSdDate(InfoUtils.dateToHexStrNoCRC());
							sendInfo.setSdTrackNo(InfoUtils.int2HexString(
									GPSareadbInfo.getTrack(), 2));
							sendInfo.setSdAreaNo(InfoUtils.int2HexString(
									GPSareadbInfo.getAreano(), 4));
							sendInfo.setSdFlag(InfoUtils
									.binaryString2HexString("0100110000000000",
											4));
							sendInfo.setSdMilCoordinate(InfoUtils
									.coor2HexString(
											GPSareadbInfo.getMile_coor(), false));
							sendInfo.setSdSpeed(InfoUtils.int2HexString(
									InfoUtils.strCal1b(gpsbdinfoNoRFID
											.getGbSpeed()), 4));
							sendInfo.setSdLon(InfoUtils.int2HexString(
									InfoUtils.strCal1bw(GPSareadbInfo.getLon()),
									8));
							sendInfo.setSdLat(InfoUtils.int2HexString(
									InfoUtils.strCal1bw(GPSareadbInfo.getLat()),
									8));
							sendInfo.setSdMilRFID("00000000");
							sendInfo.setSdStatus("01");// 00rfid计算得出 01gps计算得到
														// 02里程计算得出
							sendInfo.setSdReserve("00000000");
							LocoInfoQueue.resultToCenterVector.add(InfoUtils
									.HexToByteArr(sendInfo.toNetString()));
//							LocoInfoQueue.resultToLocoVector.add(InfoUtils.HexToByteArr(sendInfo.toRSString()));
							getInfo(sendInfo.toRSString());
							/*
							 * if (LocoInfoQueue.locoRFIDQueVecotr.size() > 0)
							 * try {
							 * LocoInfoQueue.resultToLocoVector.add(InfoUtils
							 * .HexToByteArr(sendInfo.toRSString())); } catch
							 * (Exception e) {
							 * System.out.println(e.getMessage()); }
							 */
						} catch (Exception e) {
							Log.d("LocoCalRFIDThread", "error4");
						}
					}
				}
			}
		}
	}

}
